package com.itheima.aduit.service.impl;

import com.itheima.aduit.service.ProcessService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.DeploymentBuilder;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/12/19 17:47
 */
@Service
public class ProcessServiceImpl implements ProcessService {

    @Autowired
    private RepositoryService repositoryService;

    /**
     *
     * @param file  上传的bpmn文件
     * @param companyId   企业id
     */
    @Override
    public void deployProcess(MultipartFile file,String companyId) throws IOException {
        //1. 获取上传的文件名称
        String fileName=file.getOriginalFilename();
        //2. 通过repositoryService进行流程部署
        DeploymentBuilder deploymentBuilder = repositoryService.createDeployment().addBytes(fileName, file.getBytes()).tenantId(companyId);
        Deployment deploy = deploymentBuilder.deploy();
        //3. 打印部署结果
        System.out.println("deploy = " + deploy);
    }

    /**
     * 查询所有的流程定义
     */
    @Override
    public List<ProcessDefinition> definitionList(String companyId) {
        //根据企业id查询所有的流程定义
        List<ProcessDefinition> processDefinitionList = repositoryService.createProcessDefinitionQuery().processDefinitionTenantId(companyId).latestVersion().list();
        if(CollectionUtils.isEmpty(processDefinitionList)){
            return null;
        }
        return processDefinitionList;
    }

    /**
     * 设置流程的挂起与激活
     */
    @Override
    public void setSuspendProcess(String processKey, String companyId) {
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey(processKey).processDefinitionTenantId(companyId).latestVersion().singleResult();
        if(processDefinition!=null){
            if (processDefinition.isSuspended()) {
                //挂起，将其设置为激活
                repositoryService.activateProcessDefinitionById(processDefinition.getId());
            }else{
                //将其设置为挂起
                repositoryService.suspendProcessDefinitionById(processDefinition.getId());
            }
        }

    }
}
